package com.distributeredis.redis_springboot.springapachehttpclienthttpconnectionresttemplate.httpclient.study1.doget;

import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import java.io.FileOutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class HttpClientGetTest {
    /**
     * 无参
     * @throws Exception
     */
    @Test
    public void testGet1() throws Exception {
        // 可关闭的httpclient客户端，相当于你打开的一个浏览器
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String urlStr = "https://www.baidu.com/";
        // 构造httpGet请求对象
        HttpGet httpGet = new HttpGet(urlStr);
        // 解决httpclient被认为不是真人行为
        httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
        // 防盗链，value：发生防盗链的网站的url
//        httpGet.addHeader("Referer","https://www.baidu.com/");
        // 响应
        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpGet);
            // 获取响应结果
            HttpEntity entity = response.getEntity();
            // 对httpEntity操作的工具类
            String toStr = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            System.out.println(toStr);
            // 确保
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(closeableHttpClient != null) {
                closeableHttpClient.close();
            }
            if(response != null) {
                response.close();
            }
        }
    }
    /**
     * 有参
     */
    @Test
    public void testGet2() throws Exception {
        // 可关闭的httpclient客户端，相当于你打开的一个浏览器
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String urlStr = "https://www.baidu.com/";
        String passwordParam = "234";
        // 做urlencode，如果是浏览器的话，浏览器会帮我们自动给做了
        passwordParam = URLEncoder.encode(passwordParam,StandardCharsets.UTF_8.name());
        urlStr = "http://localhost:8899/httpclient-demo/test?userName=aa&password="+passwordParam;
        // 构造httpGet请求对象
        HttpGet httpGet = new HttpGet(urlStr);
        // 解决httpclient被认为不是真人行为
        httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
        // 防盗链，value：发生防盗链的网站的url
//        httpGet.addHeader("Referer","https://www.baidu.com/");
        // 响应
        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpGet);
            // 获取响应结果
            HttpEntity entity = response.getEntity();
            // 对httpEntity操作的工具类
            String toStr = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            System.out.println(toStr);
            // 确保
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(closeableHttpClient != null) {
                closeableHttpClient.close();
            }
            if(response != null) {
                response.close();
            }
        }
    }
    /**
     * 获取响应头，content-type
     */
    @Test
    public void testGet3() throws Exception {
        // 可关闭的httpclient客户端，相当于你打开的一个浏览器
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String urlStr = "https://www.baidu.com/";
        String passwordParam = "234";
        // 做urlencode，如果是浏览器的话，浏览器会帮我们自动给做了
        passwordParam = URLEncoder.encode(passwordParam,StandardCharsets.UTF_8.name());
        urlStr = "http://localhost:8899/httpclient-demo/test?userName=aa&password="+passwordParam;
        // 构造httpGet请求对象
        HttpGet httpGet = new HttpGet(urlStr);
        // 解决httpclient被认为不是真人行为
        httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
        // 防盗链，value：发生防盗链的网站的url
//        httpGet.addHeader("Referer","https://www.baidu.com/");
        // 响应
        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpGet);
            // 获取响应头
            Header[] allHeaders = response.getAllHeaders();
            for (Header allHeader : allHeaders) {
                System.out.println("响应头名字"+allHeader.getName()+"值："+allHeader.getValue());
            }
            // 代表本次请求的成功，失败的状态
            StatusLine statusLine = response.getStatusLine();
            if(HttpStatus.SC_OK == statusLine.getStatusCode()) {
                System.out.println("响应成功");
                // 获取响应结果
                HttpEntity entity = response.getEntity();
                // contentType的值
                Header contentType = entity.getContentType();
                // 对httpEntity操作的工具类
                String toStr = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                System.out.println(toStr);
                // 确保
                EntityUtils.consume(entity);
            }else {
                System.out.println("响应失败"+statusLine.getStatusCode());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(closeableHttpClient != null) {
                closeableHttpClient.close();
            }
            if(response != null) {
                response.close();
            }
        }
    }

    /**
     * 爬取网络上的图片
     */
    @Test
    public void testGet4() throws Exception {
        // 可关闭的httpclient客户端，相当于你打开的一个浏览器
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String urlStr = "https://img2.baidu.com/it/u=1814561676,2470063876&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500";
        // 构造httpGet请求对象
        HttpGet httpGet = new HttpGet(urlStr);

        // 响应
        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpGet);
            // 代表本次请求的成功，失败的状态
            StatusLine statusLine = response.getStatusLine();
            if(HttpStatus.SC_OK == statusLine.getStatusCode()) {
                System.out.println("响应成功");
                // 获取响应结果
                HttpEntity entity = response.getEntity();
                // contentType的值
                String contentType = entity.getContentType().getValue();
                // image/jpg/ image/jpeg  image/png
                String sffix = ".jpg";
                if (contentType.contains("jpg") || contentType.contains("jpeg")) {
                    sffix = ".jpg";
                }else if (contentType.contains("bmp") || contentType.contains("bitmap")) {
                    sffix = ".bmp";
                }else if (contentType.contains("png")) {
                    sffix = ".png";
                }else if (contentType.contains("gif")) {
                    sffix = ".gif";
                }
                // 获取文件字节流
                byte[] bytes = EntityUtils.toByteArray(entity);
                String localAbsPath = "e:\\abc"+sffix;
                FileOutputStream fos = new FileOutputStream(localAbsPath);
                fos.write(bytes);
                fos.close();
                // 确保
                EntityUtils.consume(entity);
            }else {
                System.out.println("响应失败"+statusLine.getStatusCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(closeableHttpClient != null) {
                closeableHttpClient.close();
            }
            if(response != null) {
                response.close();
            }
        }
    }

    /**
     * 设置访问代理
     * @throws Exception
     */
    @Test
    public void testGet5() throws Exception {
        // 可关闭的httpclient客户端，相当于你打开的一个浏览器
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String urlStr = "https://www.baidu.com/";
        // 构造httpGet请求对象
        HttpGet httpGet = new HttpGet(urlStr);

        // 访问代理,对每一个请求进行配置，会覆盖全局的默认请求配置
        String ip = "119.108.182.217";
        int port = 9000;
        HttpHost proxy = new HttpHost(ip,port);
        RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy).build();
        httpGet.setConfig(requestConfig);

        // 响应
        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpGet);
            // 获取响应结果
            HttpEntity entity = response.getEntity();
            // 对httpEntity操作的工具类
            String toStr = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            System.out.println(toStr);
            // 确保
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(closeableHttpClient != null) {
                closeableHttpClient.close();
            }
            if(response != null) {
                response.close();
            }
        }
    }
    /**
     * 链接超时，和读取超时
     */
    @Test
    public void testGet6() throws Exception {
        // 可关闭的httpclient客户端，相当于你打开的一个浏览器
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String urlStr = "https://www.github.com/";
        // 构造httpGet请求对象
        HttpGet httpGet = new HttpGet(urlStr);

        // 访问代理,对每一个请求进行配置，会覆盖全局的默认请求配置
        RequestConfig requestConfig = RequestConfig.custom()
                // 连接超时，ms完成tcp3次握手的时间上线
                .setConnectTimeout(5000)
                // 读取超时，表示从请求的网址获取响应数据的时间间隔
                .setSocketTimeout(3000)
                // 从连接池里面获取connction的时间
                .setConnectionRequestTimeout(3000)
                .build();
        httpGet.setConfig(requestConfig);

        // 响应
        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpGet);
            // 获取响应结果
            HttpEntity entity = response.getEntity();
            // 对httpEntity操作的工具类
            String toStr = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            System.out.println(toStr);
            // 确保
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(closeableHttpClient != null) {
                closeableHttpClient.close();
            }
            if(response != null) {
                response.close();
            }
        }
    }
}
